import { defineStore } from 'pinia'
import { 
  getModelConfig, 
  updateModelConfig, 
  listModels,
  pullModel,
  getModelStatus
} from '@/api/model'

export const useModelStore = defineStore('model', {
  state: () => ({
    config: {
      endpoint: '',
      chat: {
        model: '',
        parameters: {
          temperature: 0,
          top_p: 0.1,
          top_k: 40,
          max_tokens: 2048
        }
      },
      embedding: {
        model: '',
        parameters: {
          chunkSize: 1000,
          overlap: 200,
          batchSize: 32,
          cache: true
        }
      }
    },
    availableModels: [],
    loading: false,
    modelStatus: {
      connected: false,
      chat: {
        ready: false,
        loading: false
      },
      embedding: {
        ready: false,
        loading: false
      }
    }
  }),

  actions: {
    async getConfig() {
      try {
        const response = await getModelConfig()
        this.config = response.data
        return this.config
      } catch (error) {
        console.error('Failed to get model config:', error)
        throw error
      }
    },

    async updateConfig(config) {
      try {
        const response = await updateModelConfig(config)
        this.config = response.data
        return this.config
      } catch (error) {
        console.error('Failed to update model config:', error)
        throw error
      }
    },

    async fetchModels() {
      try {
        this.loading = true
        const { data } = await listModels()
        this.availableModels = data
        return data
      } catch (error) {
        console.error('Failed to fetch models:', error)
        return []
      } finally {
        this.loading = false
      }
    },

    async pullModel(name) {
      return await pullModel(name)
    },

    async getModelStatus() {
      try {
        const { data } = await getModelStatus()
        this.modelStatus = {
          connected: Boolean(data.connected),
          chat: {
            ready: data.modelStatus === 'ready',
            loading: data.modelStatus === 'loading'
          },
          embedding: {
            ready: data.embeddingStatus === 'ready',
            loading: data.embeddingStatus === 'loading'
          }
        }
        return this.modelStatus
      } catch (error) {
        console.error('Failed to get model status:', error)
        return this.modelStatus
      }
    }
  },

  persist: true
}) 